
<template>
  <div class="info-container">
    <h2>个人信息</h2>
    <el-form :model="userForm" ref="userFormRef" class="info-form">
      <div class="avatar-section">
        <el-avatar :size="100" class="user-avatar" @click="handleAvatarClick">
          <img :src="userForm.avatar || '/default-avatar.png'" alt="用户头像" />
        </el-avatar>
        <input
          ref="avatarInput"
          type="file"
          accept="image/*"
          style="display: none"
          @change="handleAvatarUpload"
        />
        <div class="avatar-tip">点击更换头像</div>
      </div>
      
      <el-form-item label="用户名" :label-width="formLabelWidth">
        <el-input v-model="userForm.username" disabled placeholder="用户名" />
      </el-form-item>

      
      <el-form-item label="电话" :label-width="formLabelWidth" prop="phone">
        <el-input v-model="userForm.phone" placeholder="请输入电话" />
      </el-form-item>
      
      <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
        <el-input v-model="userForm.email" placeholder="请输入邮箱" type="email" />
      </el-form-item>
      
      <el-form-item class="submit-btn">
        <el-button type="primary" @click="handleSubmit" :loading="loading">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { ref, onMounted, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { getUserInfo, updateUserInfo, uploadAvatar } from '../api/auth.js';

export default {
  name: 'Info',
  setup() {
    const userFormRef = ref(null);
    const loading = ref(false);
    const formLabelWidth = '80px';
    const avatarInput = ref(null);
    
    const userForm = reactive({
      id: '',
      username: '',
      name: '',
      phone: '',
      email: '',
      avatar: ''
    });
    
    // 获取用户信息
    const fetchUserInfo = async () => {
      try {
        loading.value = true;
        const response = await getUserInfo();
        if (response.success || response.errorCode === 20000) {
          const userData = response.data || response;
          userForm.id = userData.id || '';
          userForm.username = userData.username || userData.name || '';
          userForm.phone = userData.phone || userData.mobile || '';
          userForm.email = userData.email || '';
          userForm.avatar = userData.avatar || '';
        } else {
          ElMessage.error('获取用户信息失败');
        }
      } catch (error) {
        ElMessage.error('获取用户信息失败，请稍后重试');
        console.error('获取用户信息出错:', error);
      } finally {
        loading.value = false;
      }
    };
    
    // 点击头像触发文件选择
    const handleAvatarClick = () => {
      avatarInput.value.click();
    };
    
    // 处理头像上传
    const handleAvatarUpload = async (event) => {
      const file = event.target.files[0];
      if (!file) return;
      
      // 验证文件类型和大小
      const isImage = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 2;
      
      if (!isImage) {
        ElMessage.error('请上传图片文件');
        return;
      }
      
      if (!isLt2M) {
        ElMessage.error('上传图片大小不能超过 2MB');
        return;
      }
      
      try {
        loading.value = true;
        const response = await uploadAvatar(file);
        
        if (response.success || response.errorCode === 20000) {
          // 更新头像URL
          userForm.avatar = response.data || response;
          ElMessage.success('头像上传成功');
          
          // 自动保存头像更新
          await updateUserInfo({
            id: userForm.id,
            avatar: userForm.avatar,
            email: userForm.email,
            phone: userForm.phone
          });
        } else {
          ElMessage.error(response.message || '头像上传失败');
        }
      } catch (error) {
        ElMessage.error('头像上传失败，请稍后重试');
        console.error('头像上传出错:', error);
      } finally {
        loading.value = false;
        // 清空文件输入，允许重复选择同一文件
        event.target.value = '';
      }
    };
    
    // 保存用户信息
    const handleSubmit = async () => {
      try {
        loading.value = true;
        
        // 验证表单数据
        if (!userForm.phone && !userForm.email) {
          ElMessage.warning('请至少填写电话或邮箱');
          return;
        }
        
        // 调用更新用户信息的API
        const response = await updateUserInfo({
          id: userForm.id,
          avatar: userForm.avatar,
          email: userForm.email,
          phone: userForm.phone
        });
        
        if (response.success || response.errorCode === 20000) {
          ElMessage.success('保存成功');
        } else {
          ElMessage.error(response.message || '保存失败，请稍后重试');
        }
      } catch (error) {
        ElMessage.error('保存失败，请稍后重试');
        console.error('保存用户信息出错:', error);
      } finally {
        loading.value = false;
      }
    };
    
    onMounted(() => {
      fetchUserInfo();
    });
    
    return {
      userFormRef,
      loading,
      formLabelWidth,
      userForm,
      handleSubmit,
      handleAvatarClick,
      handleAvatarUpload,
      avatarInput
    };
  }
};
</script>

<style scoped>
.info-container {
  max-width: 600px;
  margin: 40px auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.info-container h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #303133;
}

.avatar-section {
  display: flex;
  justify-content: center;
  margin-bottom: 30px;
}

.user-avatar {
  border: 2px solid #e4e7ed;
  cursor: pointer;
  transition: all 0.3s;
}

.user-avatar:hover {
  border-color: #409eff;
  transform: scale(1.05);
}

.avatar-tip {
  text-align: center;
  margin-top: 8px;
  color: #909399;
  font-size: 12px;
}

.info-form {
  width: 100%;
}

.submit-btn {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  width: 100%; /* 确保容器占满整个宽度 */
}
/* 覆盖 Element Plus 的默认样式以确保居中 */
.submit-btn :deep(.el-form-item__content) {
  justify-content: center;
}

.submit-btn .el-button {
  width: 120px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .info-container {
    margin: 20px;
    padding: 15px;
  }
  
  .formLabelWidth {
    width: 60px;
  }
}
</style>
